package cn.edu.lcu.cs.javaprogramming.gui;

import javax.swing.*;
import java.awt.event.*;

public class LoginDlg extends JDialog {
    private JPanel contentPane;
    private JButton buttonLogin;
    private JButton buttonExit;
    private JTextField usernameField;
    private JPasswordField passwordField;

    public LoginDlg() {
        setContentPane(contentPane);
        setModal(true);
        getRootPane().setDefaultButton(buttonLogin);

        buttonLogin.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //获取用户输入的用户名及密码，并进行验证
                String username = usernameField.getText();
                String password = new String(passwordField.getPassword());

                //用户名密码暂定为 lisi:123456
                if ("lisi".equals(username) && "123456".equals(password)) {
                    //登录成功
                    JOptionPane.showMessageDialog(null, "登录成功，欢迎你，" + username);
                } else {
                    //登录失败
                    JOptionPane.showMessageDialog(null, "登录失败。");
                }

                //onOK();
            }
        });

        buttonExit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        });

        // 点击 X 时调用 onCancel()
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

        // 遇到 ESCAPE 时调用 onCancel()
        contentPane.registerKeyboardAction(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    }

    private void onOK() {
        // 在此处添加您的代码
        dispose();
    }

    private void onCancel() {
        // 必要时在此处添加您的代码
        dispose();
    }

    public static void main(String[] args) {
        LoginDlg dialog = new LoginDlg();
        dialog.pack();
        dialog.setVisible(true);
        System.exit(0);
    }
}
